import os, sys
from threading import *
import config

class mplayer:
    def __init__(self, file):
        self.file = file
        self.file = self.file.replace("\ ", " ")
        self.file = self.file.replace(" ", "\ ")
        self.file = self.file.replace("(", "\(")
        self.file = self.file.replace(")", "\)")
        self.file = self.file.replace("\'", "\\\'")
        self.info = ''
        self.artist = ''
        self.name = ''
        self.album = ''
        self.genre = ''
        self.length = ''
        self.status = 'stop'
        self.tm = tm(self.file)
        self.running = self.tm.running

    def identify(self):
        bin = 'mplayer -ao null -vo null -identify -frames 0 ' + self.file + ' 2> /dev/null'
        b = os.popen(bin)
        self.info = b.readlines()
        for x in range(0, len(self.info)):
            if self.info[x][0:9] == ' Artist: ': self.artist = self.info[x][9:len(self.info[x])-1]
            if self.info[x][0:8] == ' Title: ' and self.name == '': self.name = self.info[x][8:len(self.info[x])-1]
            if self.info[x][0:7] == ' Name: ' and self.name == '': self.name = self.info[x][7:len(self.info[x])-1]
            if self.info[x][0:8] == ' Album: ': self.album = self.info[x][8:len(self.info[x])-1]
            if self.info[x][0:8] == ' Genre: ': self.genre = self.info[x][8:len(self.info[x])-1]
            if self.info[x][0:10] == 'ID_LENGTH=':
                tlength = self.info[x][10:len(self.info[x])-1]
                imin = int(tlength[0:-3])
                minutes = abs(imin/60)
                seconds = imin % 60
                milliseconds = int(tlength[-2:])
                if minutes < 10: minutes = '0' + str(minutes)
                if seconds < 10: seconds = '0' + str(seconds)
                if milliseconds < 10: milliseconds = '0' + str(milliseconds)
                self.length = str(minutes) + ':' + str(seconds) + ':' + str(milliseconds)

    def play(self):
        self.tm.play()
        self.status = 'play'

    def stop(self):
        self.tm.stop()
        self.status = 'stop'

    def update(self):
        self.running = self.tm.running

class tm(Thread):
    def __init__(self, file):
        Thread.__init__(self)
        self.file = file
        self.running = False
        # CONFIG
        self.log = ''
        self.ao = ''
        mc = config.config('mplayer.xml')
        if mc.conf.get('ao'): self.ao = '-ao ' + mc.conf.get('ao')
        if mc.conf.get('log'): self.log = ' >> ' + mc.conf.get('log')

    def run(self):
        bin = 'mplayer -fs ' + self.ao + ' '  + self.file + ' '  + self.log
        b = os.popen(bin)
        b.readlines()
        self.running = False

    def play(self):
        self.running = True
        self.start()

    def stop(self):
        bin = 'killall mplayer' + self.log
        b = os.popen(bin)
        kill = b.readline()
